package com.example.user.controller;

import com.example.user.annotation.CheckPoint;
import com.example.user.domain.UserParam;
import com.example.user.entity.User;
import com.example.user.enumerate.OperateTypeEnum;
import com.example.user.event.KeyLogEvent;
import com.example.user.event.UserNotifyEvent;
import com.example.user.util.JsonUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;

@Slf4j
@RestController
@RequestMapping("/user/api")
public class BaseController {

    @Resource
    ApplicationEventPublisher applicationEventPublisher;

    @GetMapping("/healthCheck")
    public String customerHealth() {
        return "ok";
    }

    @CheckPoint(customerNo = "#userParam.getCode()", operateType = OperateTypeEnum.REGISTER)
    @PostMapping("/p/req")
    public String postReq(@RequestHeader(value = "token") String token, @RequestBody UserParam userParam) throws JsonProcessingException {
        log.info("token={},userParam={}", token, userParam);
        userParam.setCreateTime(new Date());
        return JsonUtil.toString(userParam);
    }

    @PostMapping("/order")
    public String order(@RequestParam("userId") String userId) {
        log.info("下单操作...");
        User user = User.builder().code(userId).build();
        log.info("触发事件操作...");
        // 用户通知事件
        UserNotifyEvent userNotifyEvent = new UserNotifyEvent(user);
        applicationEventPublisher.publishEvent(userNotifyEvent);
        // 关键日志事件
        KeyLogEvent keyLogEvent = new KeyLogEvent(user);
        applicationEventPublisher.publishEvent(keyLogEvent);
        return "ok";
    }
}
